// 卡片列表页面 - 从home页面拆分出来的独立页面
import React, { lazy, Suspense } from "react";
import { useNavigate, useLocation } from 'react-router-dom';
import { useDeviceType } from '@/utils/deviceDetection';
import { useI18n } from '@/utils/in18';
import { request } from '@/utils/request';
import { showPhotoMessage } from '@/componets/photo_messagecard';

// 懒加载组件
const InformationCard = lazy(() => import("../home/components/informationCard/InformationCard"));

// 加载占位组件
const ComponentFallback = () => (
  <div className="flex items-center justify-center p-4">
    <div className="loading-skeleton w-full h-32 rounded-lg"></div>
  </div>
);

// 图片骨架屏组件
const ImageWithSkeleton: React.FC<{ src?: string; alt?: string; className?: string; style?: React.CSSProperties; priority?: boolean }> = ({ src, alt, className, style, priority }) => {
  let cache: Record<string, boolean> = {};
  if (typeof window !== 'undefined') {
    (window as any).__IMG_LOADED_CACHE = (window as any).__IMG_LOADED_CACHE || {};
    cache = (window as any).__IMG_LOADED_CACHE as Record<string, boolean>;
  }
  const initialLoaded = src ? Boolean(cache[src]) : false;
  const [loaded, setLoaded] = React.useState<boolean>(initialLoaded);
  const imgRef = React.useRef<HTMLImageElement | null>(null);
  const onLoad = () => {
    if (src && cache) cache[src] = true;
    setLoaded(true);
  };
  // 当在部分机型/网络条件下懒加载判定不触发或极慢时，做兜底，避免骨架屏长时间停留
  React.useEffect(() => {
    if (!loaded && src) {
      const id = window.setTimeout(() => setLoaded(true), 4000);
      return () => window.clearTimeout(id);
    }
  }, [src, loaded]);
  // 为首屏高优先级图片设置 fetchPriority
  React.useEffect(() => {
    try {
      if (priority && imgRef.current) {
        (imgRef.current as any).fetchPriority = 'high';
      }
    } catch {}
  }, [priority]);
  return (
    <div className='absolute inset-0 w-full h-full overflow-hidden'>
      <div className={`absolute inset-0 bg-gradient-to-br from-gray-800 via-gray-700 to-gray-900 animate-pulse ${loaded ? 'opacity-0' : 'opacity-100'} transition-opacity duration-300`} />
      {src ? (
        <img
          ref={imgRef}
          src={src}
          alt={alt}
          loading={priority ? 'eager' : 'lazy'}
          decoding='async'
          width={540}
          height={960}
          sizes={'(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 16.66vw'}
          onLoad={onLoad}
          onError={onLoad}
          className={`${className || ''} ${loaded ? 'opacity-100' : 'opacity-0'} absolute inset-0 w-full h-full object-cover transition-opacity duration-500 ease-in-out`}
          style={{ willChange: 'opacity, transform', ...style }}
        />
      ) : null}
    </div>
  );
};

type ListFilters = { keyword?: string; race?: string; category?: string; origin?: string } | undefined;
type CardItem = { id: number; title?: string; desc?: string; src?: string; raw?: any; likes_count?: number; uses_count?: number; is_liked?: boolean };

const CardsListPage: React.FC = () => {
  // 设备类型检测
  const deviceType = useDeviceType();
  const location = useLocation();
  const navigate = useNavigate();
  const { locale, t } = useI18n();
  
  const [infoVisible, setInfoVisible] = React.useState<boolean>(false); // 信息弹窗是否显示
  const [infoCard, setInfoCard] = React.useState<any | null>(null); // 信息弹窗卡片数据
  
  // 卡片列表相关状态
  const [items, setItems] = React.useState<CardItem[]>([]);
  const [page, setPage] = React.useState<number>(1);
  const pageSize = 6;
  const loadingRef = React.useRef<boolean>(false);
  const noMoreRef = React.useRef<boolean>(false);
  const seenIdsRef = React.useRef<Set<number>>(new Set());
  const likingRef = React.useRef<Record<number, boolean>>({});
  
  // 筛选条件（来自 Header 的移动端筛选弹窗）：race/category/origin/keyword
  const [filters, setFilters] = React.useState<{ keyword?: string; race?: string; category?: string; origin?: string } | null>(() => {
    try {
      const saved = sessionStorage.getItem('cards_list_filters_state');
      return saved ? JSON.parse(saved) : null;
    } catch {
      return null;
    }
  });

  // 获取数据的函数
  const fetchPage = React.useCallback(async (targetPage: number, replace = false) => {
    if (loadingRef.current) return;
    if (noMoreRef.current && !replace) return;
    loadingRef.current = true;
    try {
      const effective = filters;
      const payload: any = {
        search: effective && typeof effective.keyword === 'string' && effective.keyword.trim() ? effective.keyword.trim() : '',
        category: effective && typeof effective.category === 'string' ? effective.category : '',
        race: effective && typeof effective.race === 'string' ? effective.race : '',
        origin: effective && typeof effective.origin === 'string' ? effective.origin : '',
        name: '',
        sort: 'smart',
        page: targetPage,
        page_size: pageSize,
        language: locale || 'ey',
        "include_is_liked": true, //判断用户是否喜欢过该作品
        information: ['image_url', 'name', "uses_count", "likes_count", "role_prompt"],
      };
      const res = await request.post('/api/template/getMobileTemplatesRoute', payload);
      if (res?.data?.success === true) {
        const data = Array.isArray(res.data.data) ? res.data.data : [];
        if (replace) {
          seenIdsRef.current = new Set();
        }
        const next: CardItem[] = [];
        for (const it of data) {
          const id = typeof it?.id === 'number' ? it.id : undefined;
          if (typeof id !== 'number') continue;
          if (seenIdsRef.current.has(id)) continue;
          seenIdsRef.current.add(id);
          const url = String(it?.image_url ?? '').trim();
          if (!url) continue; // 过滤无效图片，避免骨架屏无法结束
          const title = String(it?.name ?? '');
          next.push({ id, title, src: url, raw: it, likes_count: it?.likes_count, uses_count: it?.uses_count, is_liked: Boolean(it?.is_liked) });
        }
        setItems((prev) => replace ? next : prev.concat(next));
        setPage(targetPage);
        if (data.length < pageSize) {
          noMoreRef.current = true;
        } else {
          noMoreRef.current = false;
        }
      }
    } catch (e) {
      // ignore
    } finally {
      loadingRef.current = false;
    }
  }, [filters, locale]);

  React.useEffect(() => {
    // 初次加载或筛选变化：重置并请求第一页
    noMoreRef.current = false;
    fetchPage(1, true);
  }, [filters, fetchPage]);

  // 监听 display mode 切换，切换到 list 时强制刷新列表数据
  React.useEffect(() => {
    const handler = (e: any) => {
      try {
        const mode = e?.detail?.mode;
        if (mode === 'list') {
          noMoreRef.current = false;
          seenIdsRef.current = new Set();
          fetchPage(1, true);
        }
      } catch (err) { }
    };
    window.addEventListener('home_display_mode_change', handler as any);
    return () => { try { window.removeEventListener('home_display_mode_change', handler as any); } catch { } };
  }, [fetchPage]);

  // 监听搜索结果事件
  React.useEffect(() => {
    const handleSearchResults = (e: any) => {
      try {
        const detail = e?.detail;
        if (!detail) return;
        
        const { results, search } = detail;
        if (Array.isArray(results) && results.length > 0) {
          // 有搜索结果，更新数据
          seenIdsRef.current = new Set();
          const next: CardItem[] = [];
          for (const it of results) {
            const id = typeof it?.id === 'number' ? it.id : undefined;
            if (typeof id !== 'number') continue;
            if (seenIdsRef.current.has(id)) continue;
            seenIdsRef.current.add(id);
            const url = String(it?.image_url ?? '').trim();
            if (!url) continue;
            const title = String(it?.name ?? '');
            next.push({ id, title, src: url, raw: it, likes_count: it?.likes_count, uses_count: it?.uses_count, is_liked: Boolean(it?.is_liked) });
          }
          setItems(next);
          setPage(1);
          noMoreRef.current = results.length < pageSize;
        }
        // 如果没有结果，FilterSheet 已经显示了提示，这里不需要额外处理
      } catch (e) {
        // ignore
      }
    };
    
    window.addEventListener('home_search_results', handleSearchResults as any);
    return () => {
      window.removeEventListener('home_search_results', handleSearchResults as any);
    };
  }, [pageSize]);

  // 滚动加载更多
  React.useEffect(() => {
    const handleScroll = () => {
      try {
        if (loadingRef.current || noMoreRef.current) return;
        
        // 获取正确的滚动容器
        const scrollContainer = document.getElementById('app-content-scroll');
        if (!scrollContainer) return;
        
        const scrollTop = scrollContainer.scrollTop;
        const containerHeight = scrollContainer.clientHeight;
        const scrollHeight = scrollContainer.scrollHeight;
        
        // 当滚动到距离底部200px时触发加载
        if (scrollTop + containerHeight >= scrollHeight - 200) {
          fetchPage(page + 1, false);
        }
      } catch (e) { 
        console.warn('Scroll detection error:', e);
      }
    };

    // 监听正确的滚动容器
    const scrollContainer = document.getElementById('app-content-scroll');
    if (scrollContainer) {
      scrollContainer.addEventListener('scroll', handleScroll, { passive: true });
      return () => {
        scrollContainer.removeEventListener('scroll', handleScroll);
      };
    }
  }, [page, fetchPage]);

  // 状态持久化
  const saveStateToStorage = React.useCallback((newFilters?: any) => {
    try {
      // 保存筛选条件
      if (newFilters !== undefined) {
        sessionStorage.setItem('cards_list_filters_state', JSON.stringify(newFilters));
      }

      // 保存页面状态
      const currentState = {
        timestamp: Date.now(),
        location: location.pathname
      };
      sessionStorage.setItem('cards_list_page_state', JSON.stringify(currentState));
    } catch (e) {
      console.warn('Failed to save cards list state:', e);
    }
  }, [location.pathname]);

  // 页面离开时保存状态
  React.useEffect(() => {
    const handleBeforeUnload = () => {
      saveStateToStorage(filters);
    };
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        saveStateToStorage(filters);
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [filters, saveStateToStorage]);

  // 路径变化时保存状态
  React.useEffect(() => {
    return () => {
      if (location.pathname === '/cards-list') {
        saveStateToStorage(filters);
      }
    };
  }, [location.pathname, filters, saveStateToStorage]);

  // 监听来自 Header 的筛选应用/重置事件（移动端）
  React.useEffect(() => {
    // 应用筛选：仅合并条件，数据由子组件自行拉取
    const onApply = async (e: any) => {
      const detail = e?.detail || {};
      setFilters({
        keyword: detail?.keyword,
        race: typeof detail?.race === 'string' ? detail.race : undefined,
        category: typeof detail?.category === 'string' ? detail.category : undefined,
        origin: typeof detail?.origin === 'string' ? detail.origin : undefined,
      });
    };
    // 重置筛选：回到默认参数（子组件自行拉取）
    const onReset = async () => {
      setFilters(null);
    };
    window.addEventListener('cards_list_filters_apply', onApply as any);
    window.addEventListener('cards_list_filters_reset', onReset as any);
    return () => {
      window.removeEventListener('cards_list_filters_apply', onApply as any);
      window.removeEventListener('cards_list_filters_reset', onReset as any);
    };
  }, []);

  // 监听搜索结果事件
  React.useEffect(() => {
    const handleSearchResults = (e: any) => {
      try {
        const detail = e?.detail;
        if (!detail) return;
        const { results } = detail;
        if (Array.isArray(results)) {
          saveStateToStorage(filters);
        }
      } catch { }
    };
    window.addEventListener('cards_list_search_results', handleSearchResults as any);
    return () => { window.removeEventListener('cards_list_search_results', handleSearchResults as any); };
  }, [filters, saveStateToStorage]);

  // 点击卡片时调用
  const handleCardClick = React.useCallback((card: any) => {
    setInfoCard(card);
    setInfoVisible(true);
  }, []);

  // 监听来自 message card 的导航事件
  React.useEffect(() => {
    const handler = (e: any) => {
      try {
        const d = e?.detail;
        if (!d) return;
        navigate('/CreateImage', { state: { id: d.id, name: d.name, image_url: d.image_url, role_prompt: d.role_prompt, category: d?.category } });
      } catch { }
    };
    window.addEventListener('navigate_to_create_image', handler as any);
    return () => { try { window.removeEventListener('navigate_to_create_image', handler as any); } catch { } };
  }, [navigate]);

  // 登录回跳后：如果之前在信息弹窗中触发了登录，则自动重新打开对应弹窗
  React.useEffect(() => {
    try {
      const raw = sessionStorage.getItem('login:return_state');
      if (!raw) return;
      const state = JSON.parse(raw);
      if (state?.type === 'infoCardMobile' || state?.type === 'infoCardPC') {
        if (state?.templateCard) {
          setInfoCard(state.templateCard);
          setInfoVisible(true);
        }
      }
    } catch { }
  }, []);

  // 页面卸载时清理过期的缓存数据
  React.useEffect(() => {
    const handleBeforeUnload = () => {
      try {
        const saved = sessionStorage.getItem('cards_list_page_state');
        if (saved) {
          const state = JSON.parse(saved);
          const now = Date.now();
          const oneHour = 60 * 60 * 1000;
          if (state.timestamp && (now - state.timestamp) > oneHour) {
            sessionStorage.removeItem('cards_list_data');
            sessionStorage.removeItem('cards_list_page_state');
          }
        }
      } catch (e) {
        // 忽略错误
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, []);

  return (
    <div className='w-full pb-8' style={{ border: '1px solid red' }}>
      {/* 卡片列表 */}
      <div className="relative w-full">
        <div className='w-full'>
          <ul className='grid gap-2 grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6'>
            {items.map((item, idx) => (
              <li
                key={item.id}
                onClick={(e) => {
                  e.stopPropagation();
                  handleCardClick(item);
                }}
                className={'cursor-pointer group rounded-[1rem] overflow-hidden bg-white dark:bg-[#1c1c1c] shadow'}
              >
                <div className={'relative w-full '} style={{ paddingBottom: '177.78%' }}>
                  <ImageWithSkeleton
                    src={item.src}
                    alt={`img-${item.id}`}
                    priority={idx < 6}
                    className='transform transition-transform duration-300 ease-in-out group-hover:scale-105'
                  />
                  {/* 放点赞的icon  */}
                  <div className='w-full absolute top-2 right-0 text-right' >
                    <div className='float-right mr-2 '>
                      <button
                        onClick={async (e) => {
                          try {
                            e.stopPropagation();
                            if (likingRef.current[item.id]) return;
                            likingRef.current[item.id] = true;
                            const currentLiked = Boolean(item.is_liked);
                            if (!currentLiked) {
                              // like
                              const payload = { template_id: [item.id], language: locale || 'ey' };
                              const res = await request.post('/api/template/likeTemplateRoute', payload);
                              if (res?.data?.success === true && Array.isArray(res.data.results) && res.data.results.length > 0) {
                                const r = res.data.results[0];
                                setItems((prev) => prev.map((p) => p.id === item.id ? { ...p, is_liked: Boolean(r.is_liked), likes_count: typeof r.likes_count === 'number' ? r.likes_count : p.likes_count } : p));
                                try {
                                  // 直接调用导入的消息展示函数，展示喜欢成功的 message
                                  if (r.is_liked) {
                                    showPhotoMessage({ id: item.id, title: item.title, src: item.src, raw: item.raw });
                                  }
                                } catch { }
                              }
                            } else {
                              // unlike
                              const payload = { template_id: item.id, language: locale || 'ey' };
                              const res = await request.post('/api/template/unlikeTemplateRoute', payload);
                              if (res?.data?.success === true) {
                                setItems((prev) => prev.map((p) => p.id === item.id ? { ...p, is_liked: false, likes_count: typeof res.data.likes_count === 'number' ? res.data.likes_count : p.likes_count } : p));
                              }
                            }
                          } catch (err) {
                            // ignore
                          } finally {
                            likingRef.current[item.id] = false;
                          }
                        }}
                        aria-label='like-button'
                        className='rounded-full p-1'
                      >
                        <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="18785" width="20" height="20"><path d="M512 998.4c-19.2 0-38.4-12.8-38.4-19.2C454.4 966.4 128 640 83.2 595.2 32 537.6 0 467.2 0 396.8s32-147.2 83.2-198.4c51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C492.8 211.2 505.6 224 512 236.8c6.4-12.8 19.2-25.6 32-38.4 51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C992 249.6 1024 320 1024 396.8c0 76.8-32 147.2-83.2 198.4C896 640 569.6 966.4 550.4 979.2 550.4 985.6 531.2 998.4 512 998.4z" p-id="18786" fill={item.is_liked ? '#f1a3cf' : '#ffffff'}></path></svg>
                      </button>
                    </div>
                  </div>

                  {/* 文本内容  */}
                  <div className='absolute left-0 right-0 bottom-0 px-3 py-1 bg-gradient-to-t from-black/100 to-transparent'>
                    {/* 名字  */}
                    <div className='text-[1.4rem]  font-bold text-white truncate'>{item.title}</div>
                    {/* 喜欢数量 和制作数量  */}
                    <div className='flex items-center text-[#f1a3cf]'>
                      {/* 喜欢  */}
                      <div className='text-[0.9rem] flex'>
                        {/* 喜欢的icon图标  */}
                        <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="18785" width="14" height="14"><path d="M512 998.4c-19.2 0-38.4-12.8-38.4-19.2C454.4 966.4 128 640 83.2 595.2 32 537.6 0 467.2 0 396.8s32-147.2 83.2-198.4c51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C492.8 211.2 505.6 224 512 236.8c6.4-12.8 19.2-25.6 32-38.4 51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C992 249.6 1024 320 1024 396.8c0 76.8-32 147.2-83.2 198.4C896 640 569.6 966.4 550.4 979.2 550.4 985.6 531.2 998.4 512 998.4z" p-id="18786" fill="#f1a3cf"></path></svg>
                        <span className='ml-1'>{item.likes_count}</span>
                      </div>
                      {/* 被使用次数  */}
                      <div className='text-[0.9rem] flex ml-3'>
                        <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="21885" id="mx_n_1760162359021" width="13" height="13"><path d="M977.92 945.664c21.504 0 38.912 17.408 38.912 38.912 0 10.24-4.096 20.48-11.264 27.648-7.168 7.168-17.408 11.264-27.648 11.264H47.104c-10.24 0-19.968-4.096-27.648-11.264-7.168-7.168-11.264-17.408-11.264-27.648 0-10.24 4.096-20.48 11.264-27.648 7.168-7.168 17.408-11.264 27.648-11.264H977.92zM616.448 175.104l183.296 184.32c10.24 10.24 10.24 26.624 0 36.352l-393.728 396.288c-26.112 26.112-58.88 44.544-94.72 52.224l-184.32 41.984c-28.672 6.656-54.272-20.48-45.568-49.152l52.736-179.2c9.216-31.232 26.112-59.904 48.64-82.944l397.312-399.872c4.608-5.12 11.264-7.68 18.432-7.68 6.656 0 13.312 2.56 17.92 7.68z m294.4-130.56l18.432 18.432c55.296 55.808 55.296 146.432 0 202.752l-38.4 38.4c-4.608 5.12-11.264 7.68-18.432 7.68-6.656 0-13.312-2.56-18.432-7.68l-182.784-184.32c-10.24-10.24-10.24-26.624 0-36.352l38.4-38.912c26.624-26.624 62.976-41.984 100.352-41.984 38.4 0 74.24 14.848 100.864 41.984z m0 0" p-id="21886" fill="#f1a3cf"></path></svg>
                        <span className='ml-1'>{item.uses_count}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <div className='w-full flex items-center justify-center py-4 text-sm text-gray-400'>
            {loadingRef.current ? t('home.loading') : (noMoreRef.current ? t('home.no_more') : '')}
          </div>
        </div>
      </div>
      
      <Suspense fallback={<ComponentFallback />}>
        <InformationCard visible={infoVisible} card={infoCard} onClose={() => setInfoVisible(false)} />
      </Suspense>
    </div>
  );
};

export default CardsListPage;